package com.xingzhi.common.config.elasticsearch;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;


@Configuration
public class EsConfig implements FactoryBean<TransportClient>, InitializingBean, DisposableBean {

	private Logger logger = LoggerFactory.getLogger(EsConfig.class);
	/**
	 * elk集群地址
	 */
	@Value("${elasticsearch.cluster-nodes}")
	private String hostName;
	/**
	 * 端口
	 */
	@Value("${elasticsearch.cluster-ports}")
	private String port;
	/**
	 * 集群名称
	 */
	@Value("${elasticsearch.cluster-name}")
	private String clusterName;

	/**
	 * 连接池
	 */
	@Value("${elasticsearch.pool}")
	private String poolSize;


	private TransportClient client;


	@Override
	public void destroy() throws Exception {
		try {
			logger.info("Closing elasticSearch client");
			if (client != null) {
				client.close();
			}
		} catch (final Exception e) {
			logger.error("Error closing ElasticSearch client: ", e);
		}
	}

	@Override
	public TransportClient getObject() throws Exception {
		return client;
	}

	@Override
	public Class<?> getObjectType() {
		return TransportClient.class;
	}

	@Override
	public boolean isSingleton() {
		return false;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("...........init...........");
		try {
			// 配置信息
			Settings esSetting = Settings.builder().put("cluster.name", clusterName)
					.put("client.transport.ignore_cluster_name", true) // 如果集群名不对，也能连接
					.put("client.transport.sniff", true)// 增加嗅探机制，找到ES集群
					.put("thread_pool.search.size", Integer.parseInt(poolSize))// 增加线程池个数，暂时设为10
					.build();
			client = new PreBuiltTransportClient(esSetting);
			System.out.println("...........new PreBuiltTransportClient  success...........");
			TransportAddress inetSocketTransportAddress = new TransportAddress(
					InetAddress.getByName(hostName), Integer.valueOf(port));
			client.addTransportAddress(inetSocketTransportAddress);
		} catch (Exception e) {
			logger.error("elasticsearch TransportClient create error!!!", e);
		}
	}
}
